package middleware

import (
	"github.com/gin-gonic/gin"
)

//解决浏览器跨域问题
func CORSMiddleware() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//接收来自地址：http://localhost:1016
		ctx.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		//设置客户端缓存时间
		ctx.Writer.Header().Set("Access-Control-Max-Age", "86400")
		//设置客户端访问方法 get post
		ctx.Writer.Header().Set("Access-Control-Allow-Methods", "*")
		//设置客户端访问可以携带的header
		ctx.Writer.Header().Set("Access-Control-Allow-Headers", "*")
		ctx.Writer.Header().Set("Access-Control-Expose-Headers", "*")
		//允许客户端携带认证
		ctx.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		//if ctx.Request.Method == http.MethodOptions {
		if ctx.Request.Method == "OPTIONS" {
			//ctx.AbortWithStatus(200)
			ctx.JSON(200, "Options Request!")
		} else {
			ctx.Next()
		}
	}
}
